package org.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.admin.entity.domain.File;
import org.admin.mapper.FileMapper;
import org.admin.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class IndexController {
    @Autowired
    private FileMapper mapper;
    @Autowired
    private FileService service;
    @GetMapping("/image/**")
    public ResponseEntity<Resource> image(HttpServletRequest request, HttpServletResponse response){
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String pathInfo = requestURI.substring(contextPath.length() + "/image".length());
        Resource resource = new FileSystemResource(service.UPLOAD_PATH + pathInfo);
        if(resource.exists()){
            return ResponseEntity.ok()
                    .contentType(MediaType.valueOf("image/png"))
                    // "application/octet-stream"
                    .body(resource);
        }else{
            return ResponseEntity.notFound().build();
        }
    }
}
